package com.wans.ssq.exception;

import com.wans.common.exception.CustomRunningException;
import com.wans.common.result.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
@SuppressWarnings({"all"})
public class GlobalExceptionHandler {

    // 自定义异常
    @ExceptionHandler(CustomRunningException.class)
    public ResponseEntity<Object> handleCustomRunningException(CustomRunningException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return new ResponseEntity<>(ResponseResult.fail(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);  // 500
    }


    // 处理请求方法不支持的异常
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<Object> handleMethodNotSupported(
            HttpRequestMethodNotSupportedException ex,
            HttpServletRequest request) {

        // 记录日志
        log.error(request.getRequestURI() + " - 不支持 [ " + ex.getMethod() + " ] 请求方法", ex);

        // 构建自定义响应体
        Map<String, Object> body = new HashMap<>();
        body.put("状态", HttpStatus.METHOD_NOT_ALLOWED.value());
        body.put("路径", request.getRequestURI());
        body.put("消息", "请使用正确的方式登录本站");
        body.put("错误", "不支持 [ " + ex.getMethod() + " ] 请求方法");
        body.put("时间", LocalDateTime.now());

        // 返回自定义响应和状态码
        return new ResponseEntity<>(body, HttpStatus.METHOD_NOT_ALLOWED);
    }

    /**
     * 其他未知的异常
     *
     * @param ex 未知异常信息
     * @return 错误信息
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseResult<Void>> handleOtherExceptions(Exception ex) {
        log.error(ex.getMessage());
        ex.printStackTrace();
        return new ResponseEntity<>(ResponseResult.fail(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}